import { useEffect, useState } from 'react';

import { Button, Space, Form, Row, Col, Input, Table, Select, Popconfirm, Image, Modal, Popover, DatePicker } from 'antd';
import { Access } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import { QueryJudgeListParams, Judge, JudgeReplyStatus } from './services';
import { JudgeShowStatus, queryJudgeList, delJudge, toggleJudgeShow, replyJudge } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import Ellipsis from '@/components/Ellipsis';
import StationSelect from '@/components/StationSelect';
import dayjs from 'dayjs';

const JudgePage: React.FC = () => {
  const [replyForm] = Form.useForm()
  const [searchForm] = Form.useForm<QueryJudgeListParams>()
  const [searchParams, setSearchParams] = useState<QueryJudgeListParams>({
    pageNum: 1, pageSize: 10,
    beginTime: dayjs().subtract(31, 'days').format('YYYY-MM-DD 00:00:00'),
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  })
  const judgeList = useRequest(() => queryJudgeList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delAsync } = useRequest(delJudge, {manual: true})
  const { runAsync: toggleAsync } = useRequest(toggleJudgeShow, {manual: true})
  const { runAsync: replyAsync, loading: replyLoading } = useRequest(replyJudge, {manual: true})
  const [imgList, setImgList] = useState<string[]>([])
  const [replyModal, setReplyModal] = useState<{record?: Judge}>({})

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      stationId: formValues.station ? formValues.station[0]?.id : undefined,
      stubId: formValues.stubId,
      telephone: formValues.telephone,
      beginTime: formValues.timeRange ? formValues.timeRange[0]?.format('YYYY-MM-DD HH:mm:ss') : undefined,
      endTime: formValues.timeRange ? formValues.timeRange[1]?.format('YYYY-MM-DD HH:mm:ss') : undefined,
      status: formValues.status,
      pageNum: 1,
    })
  }

  const openReplyModal = (record: Judge) => {
    setReplyModal({record})
  }

  const columns: ColumnsType<Judge> = [
    {
      title: '用户头像',
      dataIndex: 'userImg',
      width: 100,
      render: val => val && <img style={{width: 40, height: 40}} src={val} />
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      width: 140,
    },
    {
      title: '评分',
      dataIndex: 'score',
      width: 80,
    },
    {
      title: '评价内容',
      dataIndex: 'commend',
      width: 240,
      render: val => {
        return <Popover content={val} placement='topLeft'>
          <Ellipsis style={{maxWidth: 200}}>{val || '--'}</Ellipsis>
        </Popover>
      }
    },
    {
      title: '评价时间',
      dataIndex: 'createTime',
      width: 160,
    },
    {
      title: '图片',
      dataIndex: 'pics',
      width: 80,
      render: pics => {
        return pics?.length ? <a onClick={() => setImgList(pics.split(','))}>查看</a> : '--'
      }
    },
    {
      title: '回复',
      dataIndex: 'reply',
      width: 240,
      render: val => {
        return <Popover content={val} placement='topLeft'>
          <Ellipsis style={{maxWidth: 200}}>{val || '--'}</Ellipsis>
        </Popover>
      }
    },
    {
      title: '显示状态',
      dataIndex: 'hideStatus',
      width: 100,
      render: val => {
        return val && JudgeShowStatus[val]
      }
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 140,
      fixed: 'right',
      render: (id: number, record) => {
        return <Space>
          <Access accessible={!record.reply}>
            <a onClick={() => openReplyModal(record)}>回复</a>
          </Access>
          <Access accessible={record.hideStatus === JudgeShowStatus.显示}>
            <Popconfirm
              title={`确定隐藏用户: ${record.nickname} 的评论吗?`}
              onConfirm={() => toggleAsync({commentId: record.id, showStatus: JudgeShowStatus.隐藏}).then(judgeList.refresh)}
              okText="隐藏"
              cancelText="取消"
            >
              <a>隐藏</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.hideStatus === JudgeShowStatus.隐藏}>
            <Popconfirm
              title={`确定显示用户: ${record.nickname} 的评论吗?`}
              onConfirm={() => toggleAsync({commentId: record.id, showStatus: JudgeShowStatus.显示}).then(judgeList.refresh)}
              okText="显示"
              cancelText="取消"
            >
              <a>显示</a>
            </Popconfirm>
          </Access>
          <Popconfirm
            title={`确定删除用户: ${record.nickname} 的评论吗?`}
            onConfirm={() => delAsync({commentId: record.id}).then(judgeList.refresh)}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      }
    }
  ]

  const onCancel = () => {
    replyForm.resetFields()
    setReplyModal({record: undefined})
  }

  const onOk = () => {
    replyForm.validateFields()
    .then(values => {
      return replyAsync({
        commentId: replyModal.record!.id,
        content: values.content,
      })
    })
    .then(() => {
      onCancel()
      judgeList.refresh()
    })
  }

  useEffect(() => {
    const refresh = () => {
      judgeList.refresh()
    }
    window.addEventListener('refreshJudgeList', refresh)
    return () => {
      window.removeEventListener('refreshJudgeList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="form-area">
          <Form name='searchJudgeForm' form={searchForm} onFinish={onFinish} initialValues={{timeRange: [dayjs().subtract(31, 'day'), dayjs()]}}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='场站ID' name='station'>
                  <StationSelect />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备ID' name='stubId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='手机号' name='telephone'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label='评价时间' name='timeRange'>
                  <DatePicker.RangePicker showTime style={{width: '100%'}} disabledDate={current => current.isAfter(dayjs(), 'day')} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='回复状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(JudgeReplyStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={judgeList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Judge>
          rowKey='id'
          loading={judgeList.loading}
          dataSource={judgeList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: judgeList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <Image.PreviewGroup
        items={imgList}
        preview={{
          visible: imgList.length > 0,
          onVisibleChange: val => {
            if (!val) setImgList([])
          }
        }}
      >
      </Image.PreviewGroup>
      <Modal
        open={!!replyModal.record}
        title='回复评论'
        width={520}
        onCancel={onCancel}
        onOk={onOk}
        confirmLoading={replyLoading}
      >
        <Form name='replyForm' form={replyForm} layout='vertical'>
          <Form.Item name='content' label='回复内容'>
            <Input.TextArea placeholder='请输入' maxLength={200} showCount rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default JudgePage;
